<?php
namespace App\Model;
use Core\Component\Di;

class ChatGroup{
    protected $db;
    protected $tableName = 'chat_group';

    function __construct(){
        $db = Di::getInstance()->get("MYSQL");
        if($db instanceof \MysqliDb){
            $this->db = $db;
        }
    }

    public function getGroupInfo($groupId){
        if(!$groupId){
            return [];
        }
        $this->db->where("id", $groupId);
        $this->db->where("status", 1);
        $info = $this->db->getOne($this->tableName);
        if(!$info){
            return [];
        }
        return $info;
    }

    public function getOwnerGroup($ownerId){
        if(!$ownerId){
            return [];
        }
        $this->db->where("owner_id", $ownerId);
        $this->db->where("status", 1);
        $list = $this->db->get($this->tableName,NULL,'id as groupId');
        if(!$list){
            return [];
        }
        return array_column($list,'groupId');
    }

    public function addChatGroup($ownerId,$groupName){
        if(!$ownerId || !$groupName){
            return 0;
        }
        $data = Array (
            'owner_id'=>$ownerId,
            'name'=>$groupName,
            'status'=>1,
        );
        $id = $this->db->insert($this->tableName,$data);
        if(!$id){
            return 0;
        }
        (new GroupRelation())->userIntoGroup($ownerId,$id);
        return $id;
    }

    public function editChatGroup($groupId,$groupName){
        if(!$groupId || !$groupName){
            return 0;
        }
        $this->db->where("id", $groupId);
        $data['name'] = $groupName;
        $id = $this->db->update($this->tableName,$data);
        if(!$id){
            return 0;
        }
        return $groupId;
    }

    public function unsetChatGroup($groupId){
        if(!$groupId){
            return 0;
        }
        $this->db->where("id", $groupId);
        $data['status'] = -1;
        $id = $this->db->update($this->tableName,$data);
        if(!$id){
            return 0;
        }
        return $groupId;
    }

    public function searchGroupByName($key,$inGroup,$pageNum=1,$pageSize=21){
        if(!$key){
            return [];
        }
        if($inGroup){
            $this->db->where("id ",$inGroup,'not in');
        }
        $this->db->where("name", '%'.$key.'%','like');
        $column = 'id as groupId,name as groupName';
        $this->db->pageLimit = $pageSize;
        $products = $this->db->arraybuilder()->paginate($this->tableName, $pageNum,$column);
        if(!$products){
            return [];
        }
        $list['totalPage']=$this->db->totalPages;
        $list['totalCount']=$this->db->totalCount;
        $list['groups']=$products;
        return $list;
    }
}
